#!/usr/bin/env python3
# vim:fileencoding=utf-8

from netservice import ubuntuPaste as post
import os
from optparse import OptionParser
try:
  import readline
except ImportError:
  pass

def main():
  parser = OptionParser(usage='%prog [options] [image]', version="%prog 0.1")
  parser.add_option("-n", "--name",
                    dest="poster", metavar="NICK", default='',
                    help="昵称")
  parser.add_option("-i", "--image", dest="screenshot", default='',
                    help="图片文件", metavar="FILE")
  parser.add_option("-f", "--filename",
                    dest="filename", metavar="NAME", default=None,
                    help="指定文件名")
  parser.add_option("-c",
                    action="store_true", dest='comment',
                    help="附带文本(从 stdin 读入)")
  parser.add_option("-l", "--lang",
                    dest="klass", metavar="LANG", default='bash',
                    help="代码语种")

  (options, args) = parser.parse_args()
  if args:
    if len(args) == 1:
      options.screenshot = args[0]
    else:
      parser.error('错误的参数: '+' '.join(args))

  if options.filename and not options.screenshot:
    parser.error('只有当给出图片时才能使用“文件名”选项')
  user = os.environ.get('USER')
  if not options.poster:
    if user == 'lilydjwg':
      options.poster = '百合仙子'
    elif user:
      options.poster = user
    else:
      options.poster = 'anomymous'
  c = []
  if options.comment or not options.screenshot:
    while True:
      try:
        c.append(input(''))
      except EOFError:
        break
  if options.screenshot:
    url = post(
      poster     = options.poster,
      code2      = '\n'.join(c),
      screenshot = options.screenshot,
      klass      = options.klass,
      filename   = options.filename,
    )
  else:
    url = post(
      poster    = options.poster,
      code2     = '\n'.join(c),
      klass     = options.klass,
    )
  print(url)
  head, tail = url.rsplit('/', 1)
  if options.screenshot:
    print('%s/i%s' % (head, tail))
  else:
    print('%s/d%s' % (head, tail))

if __name__ == '__main__':
  try:
    main()
  except KeyboardInterrupt:
    print('中止。')
